﻿using IdentityModel.Client;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Ids4Review.ThirdParty.ClientCredentials
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            try
            {
                RequestTestAsync().Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();

        }

        private static async Task RequestTestAsync()
        {
            var authority = "http://localhost:5000";
            var disco = await DiscoveryClient.GetAsync(authority);
            if (disco.IsError)
            {
                throw new Exception("get authority error.");
            }
            var tokenClient = new TokenClient(disco.TokenEndpoint,"test_api","p@ssw0rd");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("test_api");
            if (tokenResponse.IsError)
            {
                throw new Exception("get token error.");
            }
            var accessToken = tokenResponse.AccessToken;

            var client = new HttpClient();
            client.SetBearerToken(accessToken);
            var requestUri = "http://localhost:5001/api/values";
            //var rt = await (await client.GetAsync(requestUri)).Content.ReadAsStringAsync();
            var rt = await client.GetStringAsync(requestUri);
            Console.WriteLine($"请求{requestUri},\t\n\raccess_token:{accessToken},\t\n\r结果:{rt}");
        }
    }
}
